package com.hxkj.interceptor;

import com.hxkj.domain.annotation.RequestLimit;
import com.hxkj.domain.po.CommonMessage;
import com.hxkj.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 访问限制切面
 * <p>
 * Create by chenwei on 2018/7/9 13:51
 */
@Component
@Aspect
@Slf4j
public class RequestLimitAspect {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Before("execution(public * com.hxkj.controller.*.*(..)) && @annotation(limit)")
    public void requestLimit(JoinPoint joinpoint, RequestLimit limit) {
        // 获取参数
        Object[] objects = joinpoint.getArgs();
        CommonMessage message = (CommonMessage) objects[0];
        // 获取ip
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String ip = HttpRequestUtil.getIpAddr(request);
        String url = String.valueOf(request.getRequestURL());
        // 构建redis key
        String key = "req:limit:".concat(message.getTelephone());
        // 设置ip
        message.setIp(ip);
        // 增加访问次数
        long count = redisTemplate.opsForValue().increment(key, 1);
        // 若第一次请求
        if (count == 1) {
            // 设置过期时间
            redisTemplate.expire(key, limit.time(), TimeUnit.MINUTES);
        }
        // 验证成功
        message.setLimitTag(0);
        if (count > limit.count()) {
            log.info("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
            // 验证失败
            message.setLimitTag(1);
        }
    }

}
